package com.lccviolet;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LiChaochao
 * @Date 2021/9/9 11:08
 * @Description ReenterLockDemo 可重入锁
 */
public class ReenterLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(() -> {
            phone.sendSMS();
        }, "t1").start();

        new Thread(() -> {
            phone.sendSMS();
        }, "t2").start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("=======================================");

        Thread t3 = new Thread(phone, "t3");
        Thread t4 = new Thread(phone, "t4");
        t3.start();
        t4.start();
    }
}

class Phone implements Runnable {
    // case1：证明synchronized是可重入锁
    public synchronized void sendSMS() {
        System.out.println(Thread.currentThread().getName() + " invoked sendSMS()");
        sendEmail();
    }

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + " ...... invoked sendEmail()");
    }

    // case2：证明ReentrantLock是可重入锁
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {
        lock.lock();
        // 小知识：只要lock()，unlock()匹配，加几把锁都可以；否则若不匹配，程序不会报错，但卡死没有自动结束
//        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " invoked get()");
            set();
        } finally {
            lock.unlock();
//            lock.unlock();
        }
    }

    public void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " invoked set()");
        } finally {
            lock.unlock();
        }
    }
}

